import {
    dateFormat
} from '../../../../utils/util.js'
import user from '../../../../utils/user.js'
import {
    getBindCompanySupplier,
    createDayProject,
    createMonthProject,
    getInsuranceProgramme
} from '../../../../api/app.js'

const app = getApp()
Component({
    properties: {},
    data: {
        active: 0,
        name: '', // 项目名称
        enter: '',
        enterId: '',
        date: '',
        companyList: [],
        today: '', // 不能创建今天之前的项目
        address: {},
        addressText: '',
        clockTimeText: '',
        startTime: '',
        endTime: '',
        depositDay: 1,
        tipList: false,
        dayNightFlag: 0,
        isStart: '',
        hardwareId: [],
        isInsurance: false,
        isNeedInsurance: false,
        insuranceList: false,
        signInMode: 1
    },
    created() {
        getBindCompanySupplier({
            companyId: user.companyId,
            type: 0
        }).then((res) => {
            this.setData({
                'companyList': res
            })
        })
    },
    ready() {
        this.setData({
            today: dateFormat('YYYY-mm-dd', new Date()),
            date: dateFormat('YYYY-mm-dd', new Date()),
            signInMode: user.signInMode
        })
    },
    methods: {
        switchTab0() {
            this.setData({
                active: 0
            })
        },
        switchTab1() {
            this.setData({
                active: 1
            })
        },
        tapEnter(event) {
            console.log(event.currentTarget.dataset)
            this.setData({
                'enter': event.currentTarget.dataset.name,
                'enterId': event.currentTarget.dataset.id,
                'isInsurance': event.currentTarget.dataset.insur,
                dictLabel: event.currentTarget.dataset.wesuretypename,
                dictValue: event.currentTarget.dataset.wesuretype,
                tipList: false
            })
        },
        // onEnterBlur(){
        //     setTimeout(()=>{
        //         this.setData({
        //             tipList: false
        //         })
        //     },300)
        // },
        onNameInput(event) {
            this.setData({
                name: event.detail.value
            })
        },
        onEnterTap(){
            this.setData({
                'enter': '',
                'enterId': null
            })
            this.onEnterInput({detail:{value: ''}})
        },
        onEnterInput(event) {
            const data = []
            for (const i in this.data.companyList) {
                if (this.data.companyList[i].serveCompanyName && this.data.companyList[i].serveCompanyName.indexOf(event.detail.value) !== -1) {
                    data.push(this.data.companyList[i])
                }
            }
            this.setData({
                'enter': event.detail.value,
                'enterId': null,
                tipList: data
            })
        },
        onEnterInputConfirm(event) {
            this.setData({
                'enter': event.detail.value,
                tipList: false
            })
        },
        onGoEnterprise() {
            wx.navigateTo({
                url: '/pages/enterprise/enterprise',
            })
            this.cancel()
        },
        selectDayDate(event) {
            this.setData({
                date: event.detail.value
            })
        },
        getAddPrjectDataVerify() {
            if (!this.data.name) {
                app.toast('请输入项目名称')
                return 0
            }
            if (!this.data.enter) {
                app.toast('请输入企业名称')
                return 0
            }
            if (!this.data.enterId) {
                app.confirm('该企业不存在，是否立即前往添加？').then(() => {
                    wx.navigateTo({
                        url: '/pages/enterprise/enterprise'
                    })
                })
                return 0
            }
            if (!this.data.date) {
                app.toast('请选择日期')
                return 0
            }
            return 1
        },
        onCreateDayProject() {
            if (!this.getAddPrjectDataVerify()) {
                return 0
            }
            createDayProject({
                projectName: this.data.name,
                companyId: user.companyId,
                serveCompanyName: this.data.enter,
                serveCompanyId: this.data.enterId,
                createUserId: user.userId,
                date: this.data.date,
                type: this.data.active,
                dayNightFlag: this.data.dayNightFlag,
                isOpenWesure: Number(this.data.isNeedInsurance),
                wesureTypeName: this.data.dictLabel,
                wesureType: this.data.dictValue
            }).then((res) => {
                this.triggerEvent('complete', res)
            })
        },
        onCreateMonthProject() {
            if (!this.getAddPrjectDataVerify()) {
                return 0
            }
            if (this.data.signInMode == 1 && (!this.data.address || !this.data.address.longitude || !this.data.address.current || !this.data.address.current.name)) {
                app.toast('请选择打卡地点')
                return 0
            }
            createMonthProject({
                projectName: this.data.name,
                companyId: user.companyId,
                serveCompanyName: this.data.enter,
                serveCompanyId: this.data.enterId,
                createUserId: user.userId,
                date: this.data.date,
                type: this.data.active,
                signTime: this.data.startTime + '-' + this.data.endTime,
                staffUnderpay: this.data.depositDay ? this.data.depositDay : 0,
                signPlace: this.data.address?.current?.name ?? '',
                signRange: this.data.address?.radius ?? '',
                signLocation: this.data.address ? (this.data.address.longitude + ',' + this.data.address.latitude) : '',
                dayNightFlag: this.data.dayNightFlag,
                ibeaconIds: this.data.hardwareId
            }).then((res) => {
                this.triggerEvent('complete', res)
            })
        },
        // 关闭当前组件
        cancel() {
            this.triggerEvent('cancel')
        },
        // 前往选择打卡地点
        onSelectAddress() {
            wx.navigateTo({
                url: '/packagePay/pages/clock-address/clock-address?isComponent=1'
            })
        },
        // 前往硬件打卡地点
        onSelectHardware() {
            const t = this
            wx.navigateTo({
                url: '/packagePay/pages/device-manage/device-manage?isSelect=1',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    acceptDataFromOpenedPage: function (data) {
                        console.log(data, 'data')
                        t.data.hardwareId = data.data.map(item => {
                            return item.id
                        })
                        t.setData({
                            isDeviceClock: t.data.hardwareId.length ? '已开启硬件打卡' : '',
                            hardwareId: t.data.hardwareId
                        })
                    }
                },
                success: function (res) {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        data: t.data.hardwareId
                    })
                }
            })
        },
        // 接受clock-address的调用
        selectAddressComplete(data) {
            console.log(data)
            this.setData({
                address: data,
                addressText: data.current.name
            })
        },
        onSelectTime() {
            wx.navigateTo({
                url: '/packagePay/pages/clock-time/clock-time?isComponent=1'
            })
        },
        // 接受选择打卡时间回调
        setClockTime(startTime, endTime, dayNightFlag) {
            this.setData({
                startTime,
                endTime,
                dayNightFlag: Number(dayNightFlag),
                clockTimeText: startTime + '-' + endTime + '（' + (dayNightFlag ? '夜' : '白') + '）'
            })
        },
        onSelectStartTime(event) {
            this.setData({
                startTime: event.detail.value
            })
        },
        onSelectEndTime(event) {
            this.setData({
                endTime: event.detail.value
            })
        },
        onInputDepositDay(event) {
            this.setData({
                depositDay: event.detail.value
            })
        },
        onChangeNightFlag(event) {
            this.setData({
                dayNightFlag: event.detail.value
            })
        },
        onChangeInsuranceFlag(event) {
            this.setData({
                isNeedInsurance: Number(event.detail.value)
            })
        },
        onEnterInsurance() {
            getInsuranceProgramme({
                dictType: 'saas_wesure_plan'
            }).then(res => {
                console.log(res)
                this.setData({
                    insuranceList: res
                })
            })
        },
        insuranceEnter(event) {
            this.setData({
                'dictLabel': event.currentTarget.dataset.label,
                'dictValue': event.currentTarget.dataset.value,
                insuranceList: false
            })
        },
    }
})